package jeecg.business.thread.task.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jeecg.business.entity.enter.EnterEntity;
import jeecg.business.entity.keyinfo.KeyinfoEntity;
import jeecg.business.entity.keyword.KeywordEntity;
import jeecg.business.entity.log.CollLogEntity;
import jeecg.business.entity.site.SiteEntity;
import jeecg.business.thread.task.ExecTask;

import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.clean.BaiduVideoHtmlCleanUtil;
import org.jeecgframework.core.util.clean.bean.HtmlParseResult;
import org.jeecgframework.core.util.http.HttpClientUtil;
/**
 * 
 * <p>
 * 标题: 公用抓取任务
 * </p>
 * <p>
 * 描述: // TODO
 * </p>
 * 
 * @author LinYingPiaoJian(Q:71426052)
 * @version // TODO
 * @since 2015-6-6 下午2:56:28
 */
public class BaiduVideoExecTask extends ExecTask{
	
	public static String BAIDU_VIDEO_URL = "http://v.baidu.com/v?word={keyword}&rn=40&ct=905969664&ie=utf-8&pn={page}&order=0";
	
	protected int current = 0;
	
	protected String cookies;

	public BaiduVideoExecTask(EnterEntity enter , KeywordEntity keyword, SiteEntity site) {
		super(enter , keyword, site);
	}
	
	public void setCookies(){}
	
	public String getFetchHtml() {
		String basehref = BAIDU_VIDEO_URL;
		String word;
		try {
			word = URLEncoder.encode(keyword.getKeyword(),site.getWyzfj());
			basehref = basehref.replace(KEYWORD_FLAG, word);
			return basehref;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			return null;
		}
	}
	
	public void run(){
		CollLogEntity log = null;
		log = saveLog();
		try{
			System.out.println("exec baidu video task......");
			setCookies();
			do{
				String basehref = getFetchHtml();
				basehref = basehref.replace(PAGE_FLAG , current+"");
				current++;
				System.out.println("当前页数："+current);
				if(StringUtil.isNotEmpty(basehref)){
					HtmlParseResult result = BaiduVideoHtmlCleanUtil.fetchBaiduVideo4Html(basehref, site.getWyzfj(), site, null);
					
					if(result == null || result.getChildResultList() == null) return;
					
					HtmlParseResult childResult = null;
					KeyinfoEntity keyinfo = null;
					String url = null;
					for(HtmlParseResult child : result.getChildResultList()){
						url = child.getUrl();
						
						
						
						if(!url.startsWith("http")){		//百度会二次跳转
							url = site.getGdz()+url;
							String info = HttpClientUtil.getSourceFromUrl(url, site.getNyzfj(), url);
							//<body style="display: none"><a href="http://www.iqiyi.com/v_19rro84q5g.html" id="link"></a>
							int position = info.indexOf("href=\"")+"href=\"".length();
							url = info.substring( position, info.indexOf("\"",position));
							child.setUrl(url);
						}
						
						
						if(keyinfoService.hasHref(url , enter.getId())) continue;
						try{
							if(child.getTitle().equals("石岛介绍")){
								System.out.println(1);
							}
							/**
							 * 获取时间
							 */
							Date eventdate = null;
							String info = HttpClientUtil.getSourceFromUrl(url, "utf-8", null);
							
							//如果info里有id="innerFrame"也是属于二次跳转
							if(info.contains("id=\"innerFrame\"")){
								int position = info.indexOf("src=\"")+"src=\"".length();
								url = info.substring(position, info.indexOf("\"",position));
								info = HttpClientUtil.getSourceFromUrl(url, "utf-8", null);
								child.setUrl(url);
							}
							
							String timepattern = "20[0-9]{2}[-|/年]{0,1}[0-9]{2}[-|/月]{0,1}[0-9]{2}";
							Pattern p = Pattern.compile(timepattern);
							Matcher m = p.matcher(info);
							Date now = new Date();
							while(m.find()) {
								info = m.group();
								eventdate = DataUtils.parseDate(info);
								if(eventdate.getTime()<=now.getTime()){
									break;
								}else{
									eventdate = null;
								}
							}
//							System.out.println(time);
							
							
							childResult = child;
							childResult.setCharset(site.getWyzfj());
							childResult.setType(site.getJclx());
							childResult.setLy(site.getZddz());
							childResult.setCjzd(site.getZddz());
							childResult.setSite(site.getMc());
							childResult.setKeyword(keyword.getKeyword());
							childResult.setPcfs(site.getPcfs());
							childResult.setEventDate(eventdate);
							childResult.setBodycontent(childResult.getTitle());
							keyinfo = new KeyinfoEntity(childResult);
							keyinfo.setQyid(enter.getId());
							System.out.println(keyinfo.getTitle());
							if(filter(enter, keyinfo , keyword))		//过滤
								keyinfoService.saveKeyinfo(keyinfo);
						}catch(Exception e){
							e.printStackTrace();
						}
					}
				}
			}while(current<maxpage);
		}catch(Exception e){
			e.printStackTrace();
//				log.setSfcg("2");
//				log.setCwxx(e.getMessage());
		}finally{
			log = collLogService.get(CollLogEntity.class, log.getId());
			log.setJssj(new Date());
			collLogService.updateEntitie(log);
			System.out.println("end....");
		}			
	}

	
	public static Date p (String s){
		String timepattern = "[0-9]{4}[-|/]{0,1}[0-9]{2}[-|/]{0,1}[0-9]{2}";
		Pattern p = Pattern.compile(timepattern);
		Matcher m = p.matcher(s);
		if(m.find()) {
			s = m.group();
			Date eventdate;
			try {
				eventdate = DataUtils.parseDate(s);
				return eventdate;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return null;
	}
	
	public static void main(String[] args) {
		String s1 = "陈总经理课教案上立刻到静安寺20150901大神客单价阿斯利康";
		String s2 = "陈总经理课教案上立刻到静安寺2015-09-01大神客单价阿斯利康";
		String s3 = "陈总经理课教案上立刻到静安寺2015/09/01大神客单价阿斯利康";
		
		System.out.println(p(s1));
		System.out.println(p(s2));
		System.out.println(p(s3));
	}
}
